package com.platform.module.admin.service;

import com.platform.module.common.base.CodeEnum;
import com.platform.module.common.constant.CacheConstant;
import com.platform.module.common.exception.CommonException;
import com.platform.module.common.redis.CacheClient;
import com.platform.module.common.utils.TokenGenerator;
import com.platform.module.dao.entity.TbAdminUser;
import com.platform.module.dao.mapper.TbAdminUserMapper;
import com.platform.module.pojo.admin.vo.UserInfoVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserService {

    @Resource
    private TbAdminUserMapper tbAdminUserMapper;
    @Resource
    private CacheClient cacheClient;
    @Value("${token.key}")
    private String tokenKey;

    public UserInfoVo login(String userId, String password) {

        TbAdminUser tbAdminUser = tbAdminUserMapper.selectById(userId);
        if (tbAdminUser == null) {
            throw new CommonException(CodeEnum.账号不存在);
        }

        if (!tbAdminUser.getPassword().equals(password)) {
            throw new CommonException(CodeEnum.密码错误);
        }

        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(tbAdminUser, userInfoVo);

        //生成 accessToken
        String accessToken = TokenGenerator.createToken(userId, tokenKey);
        cacheClient.set(CacheConstant.CMS_USER_TOKEN + accessToken, accessToken, TokenGenerator.TOKEN_TIME);
        userInfoVo.setAccessToken(accessToken);
        return userInfoVo;

    }

    /**
     * 退出登录
     * @param accessToken 令牌
     */
    public void logout(String accessToken) {
        cacheClient.removeKey(CacheConstant.CMS_USER_TOKEN + accessToken);
    }
}
